package com.ruoyi.web.controller.common

import com.google.code.kaptcha.Producer
import com.ruoyi.common.config.RuoYiConfig
import com.ruoyi.common.constant.CacheConstants
import com.ruoyi.common.constant.Constants
import com.ruoyi.common.core.domain.AjaxResult
import com.ruoyi.common.core.redis.RedisCache
import com.ruoyi.common.utils.sign.Base64
import com.ruoyi.common.utils.uuid.IdUtils
import com.ruoyi.system.service.ISysConfigService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.util.FastByteArrayOutputStream
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import java.awt.image.BufferedImage
import java.io.IOException
import java.util.concurrent.TimeUnit
import javax.annotation.Resource
import javax.imageio.ImageIO
import javax.servlet.http.HttpServletResponse

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
open class CaptchaController {
    @Autowired
    private lateinit var redisCache: RedisCache
    @Autowired
    private lateinit var configService: ISysConfigService

    @Resource(name = "captchaProducer")
    private lateinit var captchaProducer: Producer

    @Resource(name = "captchaProducerMath")
    private lateinit var captchaProducerMath: Producer


    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    @Throws(IOException::class)
    open fun getCode(response: HttpServletResponse?): AjaxResult {
        val ajax: AjaxResult = AjaxResult.success()
        val captchaEnabled: Boolean = configService.selectCaptchaEnabled()
        ajax["captchaEnabled"] = captchaEnabled
        if (!captchaEnabled) {
            return ajax
        }

        // 保存验证码信息
        val uuid: String = IdUtils.simpleUUID()
        val verifyKey: String = CacheConstants.CAPTCHA_CODE_KEY + uuid
        val capStr: String?
        var code: String? = null
        var image: BufferedImage? = null

        // 生成验证码
        val captchaType: String? = RuoYiConfig.captchaType
        if ("math" == captchaType) {
            val capText: String = captchaProducerMath.createText()
            capStr = capText.substring(0, capText.lastIndexOf("@"))
            code = capText.substring(capText.lastIndexOf("@") + 1)
            image = captchaProducerMath.createImage(capStr)
        } else if ("char" == captchaType) {
            code = captchaProducer.createText()
            capStr = code
            image = captchaProducer.createImage(capStr)
        }
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES)
        // 转换流信息写出
        val os = FastByteArrayOutputStream()
        try {
            ImageIO.write(image, "jpg", os)
        } catch (e: IOException) {
            return AjaxResult.error(e.message)
        }
        ajax["uuid"] = uuid
        ajax["img"] = Base64.encode(os.toByteArray())
        return ajax
    }
}
